
# -- coding: utf-8 --
import data.__init__
import  multiprocessing
from multiprocessing import Process
from airtest.aircv import *
sys.setrecursionlimit(2000)
from PyQt5 import QtWidgets,QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QTableWidgetItem, QApplication, \
    QHeaderView, QTableWidget, QCheckBox
from PyQt5.uic import loadUi
from mier_sdk import ios_device_thread
from connect_manager import Connect_Manager
import sys
from ocrtext.ocrtext import OcrHandle
path = os.getcwd()
os.chdir(path)

class Ui_MainWindow(QMainWindow):

    def __init__(self,parent = None):
        super(Ui_MainWindow,self).__init__(parent)
        print(f'----------------欢迎使用弥尔_IOS自动化SDK(教学/授权QQ群:150263510)------------')
        loadUi(os.path.join(path, r'data/uifile.ui'), self)
        self.devices_ios = set()
        self.thread_ios = dict()
        self.q = dict()
        self.check = {}
        self.CM = Connect_Manager(self)
        self.CM.my_signal_device_ios.connect(self.start_ios)
        self.CM.erro_connect.connect(self.log)
        self.CM.start()
        file_dir = os.path.join(path, 'scripts')
        files_list = []
        for files in os.listdir(file_dir):
            if '.py' in files:
                files_list.append(files)
                #print(files)
        self.comboBox.addItems(files_list)
        #self.comboBox.activated.connect(self.add_files)
        self.pushButton_4.clicked.connect(self.open_script_dir)
        self.pushButton_2.clicked.connect(self.open_images_dir)
        self.pushButton_11.clicked.connect(self.check_all_true)
        self.pushButton_5.clicked.connect(self.shuaxin)
        self.pushButton_12.clicked.connect(self.check_all_false)
        self.pushButton_3.clicked.connect(self.stop_ios_script)
        self.pushButton_9.clicked.connect(self.start_WDA)
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        QTableWidget.resizeRowsToContents(self.tableWidget)





    def start_WDA(self):
        for udid in self.check.keys():
            if self.check[udid].isChecked():
                try:
                    self.q[udid] = multiprocessing.Queue(maxsize=100)
                    if udid in self.thread_ios.keys() :
                        self.thread_ios[udid].kill()
                    scripts_name = self.comboBox.currentText().split('.py')[0]


                    #开发者后台设备管理中生成
                    mier_secret = 'kotgsanshao'
                    mier_api_key = '26c379af-8ac1-4e7a-bca2-1e07c72a59ab'
                    #mier_secret,mier_api_key  开发者SDK秘钥和项目标识  用于作者设备授权


                    self.thread_ios[udid] = Process(target=ios_device_thread.script, args=(mier_secret, mier_api_key, udid, self.q[udid], OcrHandle, scripts_name,))
                    self.thread_ios[udid].daemon = True
                    self.thread_ios[udid].start()
                except Exception as e:
                    self.log_3([udid,f'开始脚本报错:{e}'])
                    print("开始运行脚本报错7:", e)

    #全部取消
    def check_all_false(self):
        for key in self.check.keys():
            if self.check[key].isChecked():
                self.check[key].setChecked(False)

    # 全部选中
    def check_all_true(self):
        for key in self.check.keys():
            if not self.check[key].isChecked():
                self.check[key].setChecked(True)


    def shuaxin(self):

        file_dir = os.path.join(path,'scripts')
        files_list = []
        for files in os.listdir(file_dir):
            if '.py' in files:
                files_list.append(files)
        self.comboBox.clear()
        print('刷新脚本')
        self.comboBox.addItems(files_list)


    def open_images_dir(self):
        path = os.getcwd()
        os.startfile(os.path.join(path,r'images'))

    def open_script_dir(self):
        path = os.getcwd()
        os.startfile(os.path.join(path, r'scripts'))


    def stop_ios_script(self):
        for udid in self.check.keys():
            if self.check[udid].isChecked():
                try:
                    if self.thread_ios[udid]:
                        print('停止脚本')
                        self.thread_ios[udid].kill()
                        self.log_3([udid, '脚本运行结束'])
                        del self.thread_ios[udid]

                except Exception as e:
                    print("停止脚本报错:", e)


    def log_3(self,data):
        try:
            count = self.tableWidget.rowCount()
            if count > 0 :
                for i in range(0,count):
                    if self.tableWidget.item(i,1).text() == str(data[0]):
                        self.tableWidget.setItem(i,4,QTableWidgetItem(str(data[1])))
                        break
        except Exception as e:
            print('数据1234使用不对!!')

    def log_6(self, data):
        try:
            count = self.tableWidget.rowCount()
            if count > 0:
                for i in range(0, count):
                    if self.tableWidget.item(i, 1).text() == str(data[0]):
                        self.tableWidget.setItem(i, 7, QTableWidgetItem(str(data[1])))
                        break
        except Exception as e:
            print('数据1234使用不对!!')

    def log(self, data):
        if data[1] == 1:
            self.log_1([data[0],data[2]])
        elif data[1] == 2:
            self.log_2([data[0],data[2]])
        elif data[1] == 3:
            self.log_3([data[0],data[2]])
        elif data[1] == 4:
            self.log_4([data[0],data[2]])
        elif data[1] == 6:
            self.log_6([data[0],data[2]])

    #USB 日志
    def log_2(self,data):
        try:
            count = self.tableWidget.rowCount()
            if count > 0:
                for i in range(0, count):
                    if self.tableWidget.item(i, 1).text() == data[0]:
                        self.tableWidget.setItem(i, 3, QTableWidgetItem(data[1]))
                        break
        except Exception as e:
            print('数据1234使用不对!!')
    # USB 日志
    def log_1(self, data):
        try:
            count = self.tableWidget.rowCount()
            if count > 0:
                for i in range(0, count):
                    if self.tableWidget.item(i, 1).text() == data[0]:
                        self.tableWidget.setItem(i,2, QTableWidgetItem(data[1]))
                        break
        except Exception as e:
            print('数据1234使用不对!!')

        # USB 日志

    def log_4(self, data):
        try:
            count = self.tableWidget.rowCount()
            if count > 0:
                for i in range(0, count):
                    if self.tableWidget.item(i, 1).text() == data[0]:
                        self.tableWidget.setItem(i, 5, QTableWidgetItem(data[1]))
                        break
        except Exception as e:
            print('数据1234使用不对!!')

    def start_ios(self,udid_info):
        udid = udid_info[0]
        name = udid_info[1]
        count = self.tableWidget.rowCount()
        is_new = True
        if count > 0:
            for i in range(0, count):
                if self.tableWidget.item(i, 1).text() == udid:
                    #self.tableWidget.setItem(i, 3, QTableWidgetItem("wda重新连接"))
                    is_new = False
                    self.tableWidget.setItem(i, 0, QTableWidgetItem(name))
                    self.tableWidget.setItem(i, 1, QTableWidgetItem(udid))
                    self.tableWidget.setItem(i, 2, QTableWidgetItem(''))
                    self.tableWidget.setItem(i, 3, QTableWidgetItem('USB已连接'))
                    self.tableWidget.setItem(i, 4, QTableWidgetItem(''))
                    self.tableWidget.setItem(i, 5, QTableWidgetItem(''))
                    self.tableWidget.setCellWidget(i, 6, self.check_btn(udid))
                    self.tableWidget.setItem(i,7, QTableWidgetItem(''))
                    break

        if is_new:
            self.tableWidget.setRowCount(count + 1)
            self.tableWidget.setItem(count, 0, QTableWidgetItem(name))
            self.tableWidget.setItem(count, 1, QTableWidgetItem(udid))
            self.tableWidget.setItem(count, 2, QTableWidgetItem(''))
            self.tableWidget.setItem(count, 3, QTableWidgetItem('USB已连接'))
            self.tableWidget.setItem(count, 4, QTableWidgetItem(''))
            self.tableWidget.setItem(count, 5, QTableWidgetItem(''))
            self.tableWidget.setCellWidget(count, 6, self.check_btn(udid))
            self.tableWidget.setItem(count, 7, QTableWidgetItem(''))
        self.tableWidget.sortItems(0, Qt.AscendingOrder)

    #
    # def snaphot_ios(self,uuid,name):
    #     self.log_3([uuid,'开始截图'])
    #     png_name =os.path.join(path,'images',rf'{name}_shot.png')
    #     with open(png_name, 'w') :
    #
    #         print('png_name:', png_name)
    #         tidevice.Device(uuid).screenshot(png_name)
    #         rotate_img(png_name)
    #
    #     self.log_3([uuid, '完成截图'])


    def window_out(self,str2):
        QtWidgets.QMessageBox.critical(self,"",str2)


    def check_btn(self,udid):
        cb = QCheckBox()
        self.check[udid] = cb
        return cb
    #
    # def buttonForRow(self,uuid,name):
    #     widget = QWidget()
    #
    #     self.btn_截图[uuid] = QPushButton('截图')
    #     self.btn_截图[uuid].setStyleSheet(f'''text-align:center;
    #     background-color:yellow;
    #     height : 30px;
    #     border-style:outset;
    #     font :13px''')
    #
    #     self.btn_截图[uuid].clicked.connect(lambda: self.snaphot_ios(uuid,name,))
    #     btn = self.btn_截图[uuid]
    #
    #     hLayout = QHBoxLayout()
    #     hLayout.addWidget(btn)
    #     hLayout.setContentsMargins(5,2,5,2)
    #     widget.setLayout(hLayout)
    #     return widget
    #


if __name__ == '__main__':
    multiprocessing.freeze_support()
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    ui = Ui_MainWindow()
    ui.show()
    sys.exit(app.exec_())








